package cn.xuqiudong.rpc.registry.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import cn.xuqiudong.rpc.cluster.exception.XqdCommonException;
import cn.xuqiudong.rpc.registry.Registry;
import cn.xuqiudong.rpc.registry.RegistryFactory;

import java.util.concurrent.TimeUnit;

/**
 * 描述:基于zookeeper的注册中心工厂
 * @author Vic.xu
 * @date 2022-02-15 11:38
 */
public class ZookeeperRegistryFactory implements RegistryFactory {

    private CuratorFramework client;

    @Override
    public Registry getRegistry(String address) {
        try {

            CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder().connectString(address)
                    .retryPolicy(new RetryNTimes(1, 1000))
                    .connectionTimeoutMs(5000).sessionTimeoutMs(60000);
            this.client = builder.build();
            //TODO 注册一些事件 CuratorZookeeperClient
            this.client.start();
            boolean connected = this.client.blockUntilConnected(5000, TimeUnit.MILLISECONDS);
            if (!connected) {
                throw new XqdCommonException("Unable to connect to zookeeper");
            }

            return new ZookeeperRegistry(address, new XqdZookeeperClient(client));
        } catch (Exception e) {
            throw new XqdCommonException("zookeeper registration center registration failed address=" + address, e);
        }
    }
}
